package com.example.dzbsh.controller;


import com.example.dzbsh.model.*;
import com.example.dzbsh.service.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.dzbsh.util.JsonResult;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.*;

@RestController
@RequestMapping("daoru")
public class DaoruController {

    @Resource
    DaoruService ddDaoruService;

    @Resource
    DictJingshangleixingService ddDictJingshangleixingService;

    @Resource
    DictZhiwuService ddDictZhiwuService;

    @Resource
    DictJingyingzhuangtaiService ddDictJingyingzhuangtaiService;

    @Resource
    ChaheQingkuangService ddChaheQingkuangService;

    @Resource
    CaozuojiluService ddCaozuojiluService;


    private Logger logger = LoggerFactory.getLogger(getClass());

    // 导入经商情况
    @RequestMapping("jingshangqingkuang")
    public JsonResult<?> Jingshangqingkuang(@RequestParam("fileurl") String ppFileurl,
                                            HttpServletRequest request) {
        try {
            HttpSession session = request.getSession();
            if (session == null || session.getAttribute("DeptId") == null) {
                return JsonResult.getErrorResult("尚未登录,获取单位信息失败");
            }
            String ppDeptId= session.getAttribute("DeptId").toString();

            JsonResult mmIsok = ddDaoruService.DaoruJingshangQingkuang(ppDeptId,ppFileurl);
            if(mmIsok.getResult().equals("1")){
                return JsonResult.getSuccessResult(mmIsok.getResultContent());
            }else{
                return JsonResult.getErrorResult(mmIsok.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.getErrorResult("daoru/jingshangqingkuang:error " + e.getMessage());
        }
    }

    // 得到excel中的数据
    @SuppressWarnings("resource")
    @RequestMapping("get_chahevalue")
    public JsonResult<?> get_value(
            @RequestParam("fileurl") String mmFileUrl,
            HttpServletRequest request
    ){
        try {
            HttpSession session = request.getSession();
            if (session == null || session.getAttribute("DeptId") == null) {
                return JsonResult.getErrorResult("尚未登录,获取单位信息失败");
            }
            String ppDeptId= session.getAttribute("DeptId").toString();

            //取出文档存放的根目录，并去除文件最后的斜杠
            String mmWenjian = mmFileUrl.split("userfiles")[1];
            String url = "./userfiles"+mmWenjian;

            Workbook book = null;

            File f = new File(url);
            InputStream in = new FileInputStream(f);

            String prefix = url.substring(url.lastIndexOf(".")+1);
            if(prefix.equals("xls")) {
                book = new HSSFWorkbook(in);
            }else if(prefix.equals("xlsx")) {
                book = new XSSFWorkbook(in);
            }else {
                return JsonResult.getErrorResult("请上传xls或xlsx类型的文件！");
            }

            Sheet sheet = book.getSheetAt(0);
            int column= sheet.getRow(0).getPhysicalNumberOfCells();
            int rows = sheet.getPhysicalNumberOfRows();

            //List<Map<String,Object>> mmReturnList = new ArrayList<Map<String,Object>>();

            List<DictJingshangleixing> mmJingshangleixing = ddDictJingshangleixingService.findAll();
            List<DictZhiwu> mmZhiwu = ddDictZhiwuService.findAll();
            List<DictJingyingzhuangtai> mmJingyingzhuangtai = ddDictJingyingzhuangtaiService.findAll();


            for (int i = 1; i < rows ; i++) { //行

                Map<String,Object> mmMap = new HashMap<>();
                String mm序号 = getCellFormatValue(sheet.getRow(i).getCell(0))==null?"":getCellFormatValue(sheet.getRow(i).getCell(0)).toString().trim();
                String mm姓名 = getCellFormatValue(sheet.getRow(i).getCell(1))==null?"":getCellFormatValue(sheet.getRow(i).getCell(1)).toString().trim();
                String mm身份证号 = getCellFormatValue(sheet.getRow(i).getCell(2))==null?"":getCellFormatValue(sheet.getRow(i).getCell(2)).toString().trim();
                String mm企业名称 = getCellFormatValue(sheet.getRow(i).getCell(3))==null?"":getCellFormatValue(sheet.getRow(i).getCell(3)).toString().trim();
                String mm社会信用代码 = getCellFormatValue(sheet.getRow(i).getCell(4))==null?"":getCellFormatValue(sheet.getRow(i).getCell(4)).toString().trim();
                String mm经商类型 = getCellFormatValue(sheet.getRow(i).getCell(5))==null?"":getCellFormatValue(sheet.getRow(i).getCell(5)).toString().trim();
                String mm经营范围 = getCellFormatValue(sheet.getRow(i).getCell(6))==null?"":getCellFormatValue(sheet.getRow(i).getCell(6)).toString().trim();
                String mm经营状态 = getCellFormatValue(sheet.getRow(i).getCell(7))==null?"":getCellFormatValue(sheet.getRow(i).getCell(7)).toString().trim();
                String mm职务 = getCellFormatValue(sheet.getRow(i).getCell(8))==null?"":getCellFormatValue(sheet.getRow(i).getCell(8)).toString().trim();
                String mm认缴出资 = getCellFormatValue(sheet.getRow(i).getCell(9))==null?"":getCellFormatValue(sheet.getRow(i).getCell(9)).toString().trim();
                String mm前五商品或服务 = getCellFormatValue(sheet.getRow(i).getCell(10))==null?"":getCellFormatValue(sheet.getRow(i).getCell(10)).toString().trim();
                String mm前五交易对象 = getCellFormatValue(sheet.getRow(i).getCell(11))==null?"":getCellFormatValue(sheet.getRow(i).getCell(11)).toString().trim();
                String mm是否同军队有经济利益关系 = getCellFormatValue(sheet.getRow(i).getCell(12))==null?"":getCellFormatValue(sheet.getRow(i).getCell(12)).toString().trim();
                String mm军队名称 = getCellFormatValue(sheet.getRow(i).getCell(13))==null?"":getCellFormatValue(sheet.getRow(i).getCell(13)).toString().trim();
                String mm近三年直接发生经济利益关系的军队名称 = getCellFormatValue(sheet.getRow(i).getCell(14))==null?"":getCellFormatValue(sheet.getRow(i).getCell(14)).toString().trim();

                // 获得经商类型的id
                String mmLeixingId = "99";
                for (int js = 0;js<mmJingshangleixing.size();js++){
                      if(mm经商类型.equals(mmJingshangleixing.get(js).getText())){
                          mmLeixingId=mmJingshangleixing.get(js).getId();
                          break;
                      }
                }

                // 获得经营状态的id
                String mmZhuangtaiId = "99";
                for (int zt = 0;zt<mmJingyingzhuangtai.size();zt++){
                    if(mm经营状态.equals(mmJingyingzhuangtai.get(zt).getText())){
                        mmZhuangtaiId=mmJingyingzhuangtai.get(zt).getId();
                        break;
                    }
                }

                // 获得职务的id
                String mmZhiwuId = "99";
                for (int zw = 0;zw<mmZhiwu.size();zw++){
                    if(mm职务.equals(mmZhiwu.get(zw).getText())){
                        mmZhiwuId=mmZhiwu.get(zw).getId();
                        break;
                    }
                }
                // 创建查核数据对象
                ChaheQingkuang mmChahe = new ChaheQingkuang();
                mmChahe.setIsvalid(1);
                mmChahe.setJingyingfanwei(mm经营范围); // 经营范围
                mmChahe.setJingyingzhuangtai(mmZhuangtaiId); // 经营状态
                mmChahe.setJingyingzhuangtaitext(mm经营状态);  //经营状态text
                mmChahe.setJinsanzhijieguanximingcheng(mm近三年直接发生经济利益关系的军队名称); // 近三年发生经济利益关系的军队名称
                mmChahe.setLeixing(mmLeixingId); // 类型id
                mmChahe.setLeixingtext(mm经商类型); // 经商类型text
                mmChahe.setQianwujiaoyiduixiangname(mm前五交易对象); //前五交易对象
                mmChahe.setQianwushangpinhuofuwuname(mm前五商品或服务);// 前五商品或服务
                mmChahe.setShenfenzhenghao(mm身份证号); // 身份证号
                mmChahe.setQiyename(mm企业名称); // 企业名称
                mmChahe.setRenjiaochuzie(mm认缴出资); // 认缴出资
                mmChahe.setShifouyouzhijieguanxi(getShifou(mm是否同军队有经济利益关系)); //是否和军队存在经济利益关系
                mmChahe.setShijunduimingcheng(mm军队名称); // 存在关系的军队名称
                mmChahe.setZhiwu(mmZhiwuId); // 职务id
                mmChahe.setZhiwutext(mm职务); // 职务
                mmChahe.setJiashuname(mm姓名); // 家属名称
                mmChahe.setText1(mm社会信用代码);

                // 对本条查核数据判断和导入
                ddChaheQingkuangService.addAndDeleteOld(mmChahe);

            }
            // 添加操作纪律
            Caozuojilu mmCaozuojilu = new Caozuojilu();
            mmCaozuojilu.setChahenumber(rows-1);
            mmCaozuojilu.setDeptid(ppDeptId);
            mmCaozuojilu.setUpdatetime(new Date());
            mmCaozuojilu.setLeixing("chahe");
            mmCaozuojilu.setId(UUID.randomUUID().toString());
            ddCaozuojiluService.add(mmCaozuojilu);

            in.close();
            return JsonResult.getSuccessResult("导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("daoru/get_chahevalue:error ", e);
            return JsonResult.getErrorResult("daoru/get_chahevalue:error " + e.getMessage());
        }
    }

    // 删除了时间类型的判定
    private Object getCellFormatValue(Cell cell) {
        Object cellvalue = "";
        if (cell != null) {
            // 判断当前Cell的Type
            switch (cell.getCellType()) {
                case Cell.CELL_TYPE_NUMERIC:// 如果当前Cell的Type为NUMERIC
                case Cell.CELL_TYPE_FORMULA: {

                    cell.setCellType(1);
                    cellvalue=cell.getStringCellValue();

                    break;
                }
                case Cell.CELL_TYPE_STRING:// 如果当前Cell的Type为STRING
                    // 取得当前的Cell字符串
                    cellvalue = cell.getRichStringCellValue().getString();
                    break;
                default:// 默认的Cell值
                    cellvalue = "";
            }
        } else {
            cellvalue = "";
        }
        return cellvalue;
    }

    // 导入甄别情况
    @RequestMapping("zhenbieqingkuang")
    public JsonResult<?> Zhenbieqingkuang(@RequestParam("fileurl") String ppFileurl,
                                          HttpServletRequest request) {
        try {
            HttpSession session = request.getSession();
            if (session == null || session.getAttribute("DeptId") == null) {
                return JsonResult.getErrorResult("尚未登录,获取单位信息失败");
            }
            String ppDeptId= session.getAttribute("DeptId").toString();

            JsonResult mmIsok = ddDaoruService.DaoruZhenbieQingkuang(ppDeptId,ppFileurl);
            if(mmIsok.getResult().equals("1")){
                return JsonResult.getSuccessResult(mmIsok.getResultContent());
            }else{
                return JsonResult.getErrorResult(mmIsok.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.getErrorResult("daoru/zhenbieqingkuang:error " + e.getMessage());
        }
    }

    // 导入规范落实情况
    @RequestMapping("guifanqingkuang")
    public JsonResult<?> Guifanqingkuang(@RequestParam("fileurl") String ppFileurl,
                                         HttpServletRequest request) {
        try {
            HttpSession session = request.getSession();
            if (session == null || session.getAttribute("DeptId") == null) {
                return JsonResult.getErrorResult("尚未登录,获取单位信息失败");
            }
            String ppDeptId= session.getAttribute("DeptId").toString();

            JsonResult mmIsok = ddDaoruService.DaoruGuifanQingkuang(ppDeptId,ppFileurl);
            if(mmIsok.getResult().equals("1")){
                return JsonResult.getSuccessResult(mmIsok.getResultContent());
            }else{
                return JsonResult.getErrorResult(mmIsok.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.getErrorResult("daoru/Guifanqingkuang:error " + e.getMessage());
        }
    }

    private int  getShifou(String mmShifou){

        if("是".equals(mmShifou)){
           return 1;
        }
        return 0;
    }
}
